import { ApiGetCityList } from '@/api/city'

// const DEFAULT_CITY = {
//     adcode: "510107",
//     center: "104.065735,30.657299",
//     cityCode: "510107",
//     name: "成都市"
//   }
export const getLocation = async () => {
    try {
      const { error, result: cityList = [] } = await ApiGetCityList();
  
      uni.getLocation({
        type: 'gcj02',
        success(res) {
          const { longitude, latitude } = res;
          console.log('定位信息:', res);
  
          // 调用高德逆地理编码 API
          uni.request({
            url: `https://restapi.amap.com/v3/geocode/regeo`,
            method: 'GET',
            data: {
              key: '7367d4e858a51c328ce549ac315007d0',
              location: `${longitude},${latitude}`,
              extensions: 'all'
            },
            success(regeoRes) {
              const addressComponent = regeoRes.data?.regeocode?.addressComponent;
              console.log('高德逆地理返回:', addressComponent);
  
              if (!addressComponent) {
                console.warn('逆地理失败或无结果，使用默认城市');
                $store.commit('setCity', DEFAULT_CITY);
                return;
              }
  
              const cityCode = addressComponent.citycode || addressComponent.adcode;
              const cityName = addressComponent.city || addressComponent.province;
              
              let cityItem = cityList.find(i => i.citycode === cityCode);
  
              if (!cityItem && cityName) {
                cityItem = cityList.find(i => i.name.includes(cityName));
              }
  
              if (!cityItem) {
                console.warn('无法根据逆地理找到城市，使用默认');
                cityItem = DEFAULT_CITY;
              }
  
              $store.commit('setCity', {
                adcode: cityItem.adcode,
                cityCode: cityCode || cityItem.citycode,
                name: cityName,
                center: `${longitude},${latitude}`,
              });
            },
            fail(err) {
              console.error('逆地理API失败', err);
              $store.commit('setCity', DEFAULT_CITY);
            }
          });
        },
        fail(err) {
          console.error('定位失败', err);
          $store.commit('setCity', DEFAULT_CITY);
        }
      });
    } catch (err) {
      console.error('城市数据获取失败', err);
      $store.commit('setCity', DEFAULT_CITY);
    }
  };